import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

// 发送好友请求
export async function POST(req: Request) {
  try {
    const { receiverId } = await req.json()
    const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
    const senderId = await getCurrentUserId(token)

    if (!senderId) {
      return NextResponse.json(
        {
          success: false,
          message: '未登录用户'
        },
        { status: HttpStatus.UNAUTHORIZED }
      )
    }

    // 检查是否已经是好友
    const existingFriend = await prisma.friend.findFirst({
      where: {
        OR: [
          { senderId, receiverId },
          { senderId: receiverId, receiverId: senderId }
        ]
      }
    })

    if (existingFriend) {
      return NextResponse.json({
        success: false,
        message: '已经是好友了'
      })
    }

    // 检查是否已经发送过请求
    const existingRequest = await prisma.friendRequest.findFirst({
      where: {
        senderId,
        receiverId,
        status: 'pending'
      }
    })

    if (existingRequest) {
      return NextResponse.json({
        success: false,
        message: '已经发送过好友请求了'
      })
    }

    // 创建好友请求
    await prisma.friendRequest.create({
      data: {
        senderId,
        receiverId,
        status: 'pending'
      }
    })

    return NextResponse.json({
      success: true,
      message: '好友请求已发送'
    })
  } catch (error) {
    console.error('Send friend request failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '发送好友请求失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}

// 获取好友请求列表
export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url)
    const page = Number(searchParams.get('page')) || 1
    const pageSize = Number(searchParams.get('pageSize')) || 10
    const keyword = searchParams.get('keyword') || ''
    const type = searchParams.get('type') || 'received'
    const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
    const currentUserId = await getCurrentUserId(token)

    // 构建查询条件
    const where = {
      ...(type === 'received'
        ? { receiverId: currentUserId } // 查询发给我的请求
        : { senderId: currentUserId }), // 查询我发出的请求
      ...(keyword && {
        OR:
          type === 'received'
            ? [{ sender: { username: { contains: keyword } } }, { sender: { nickname: { contains: keyword } } }]
            : [{ receiver: { username: { contains: keyword } } }, { receiver: { nickname: { contains: keyword } } }]
      })
    }

    // 查询总数
    const total = await prisma.friendRequest.count({ where })

    // 查询列表
    const list = await prisma.friendRequest.findMany({
      where,
      // include 表示查询关联表的数据
      include: {
        // sender关联到User表
        sender: {
          // select 表示只返回User表中的这些字段
          select: {
            id: true,
            username: true,
            nickname: true,
            gender: true,
            avatar: true
          }
        },
        receiver: {
          select: {
            id: true,
            username: true,
            nickname: true,
            gender: true,
            avatar: true
          }
        }
      },
      skip: (page - 1) * pageSize,
      take: pageSize,
      orderBy: {
        createdAt: 'desc'
      }
    })

    return NextResponse.json({
      success: true,
      data: {
        list,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    })
  } catch (error) {
    console.error('Get friend requests failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '获取好友请求列表失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
